package com.androider.timememory.sms;

import com.androider.timememory.sms.SMSHandler;
import com.androider.timememory.utils.SMSUtil;

import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Message;

public class SMSObserver extends ContentObserver {
	private ContentResolver mResolver;
	private SMSHandler mHandler;
	
	private static final String[] PROJECTION = new String[]  
	                                                      {  
	                                                          SMSUtil.ID,//0  
	                                                          SMSUtil.TYPE,//1  
	                                                          SMSUtil.ADDRESS,//2  
	                                                          SMSUtil.BODY,//3  
	                                                          SMSUtil.DATE,//4  
	                                                          SMSUtil.THREAD_ID,//5  
	                                                          SMSUtil.READ,//6  
	                                                          SMSUtil.PROTOCOL//7  
	                                                      };
	
	private static final String SELECTION =  
		SMSUtil.THREAD_ID  + " > %s" +  " and " + SMSUtil.READ + " = " + SMSUtil.MESSAGE_UNREAD +
	    " and (" + SMSUtil.TYPE + " = " + SMSUtil.MESSAGE_TYPE_INBOX +  
	    " or " + SMSUtil.TYPE + " = " + SMSUtil.MESSAGE_TYPE_SENT + ")";
	
    private static int MAX_ID = 0; 
	
	public SMSObserver(ContentResolver contentResolver, SMSHandler handler) {
		super(handler);
		mResolver = contentResolver;
		mHandler = handler;
	}
	
	@Override
	public void onChange(boolean selfChange) {
		super.onChange(selfChange);
		
		Cursor cursor = mResolver.query(SMSUtil.CONTENT_URI, PROJECTION,  
		        String.format(SELECTION, MAX_ID), null, null);
		
		int id, threadId, type, protocol;  
        String address, body;
        Message msg;
        
		while(cursor.moveToNext()) {
			id = cursor.getInt(cursor.getColumnIndex(SMSUtil.ID));
			threadId = cursor.getInt(cursor.getColumnIndex(SMSUtil.THREAD_ID));
	        type = cursor.getInt(cursor.getColumnIndex(SMSUtil.TYPE));
	        address = cursor.getString(cursor.getColumnIndex(SMSUtil.ADDRESS));  
	        body = cursor.getString(cursor.getColumnIndex(SMSUtil.BODY));  
	        protocol = cursor.getInt(cursor.getColumnIndex(SMSUtil.PROTOCOL));

	        if(protocol == SMSUtil.PROTOCOL_SMS && body != null) {
	        	SMS sms = new SMS();
		        sms.setId(id);
		        sms.setThreadId(threadId);
		        sms.setType(type);
		        sms.setAddress(address.replace("+86", ""));
		        sms.setBody(body);
		        sms.setProtocol(protocol);
		        
		        msg = new Message();
		        msg.obj = sms;
		        mHandler.sendMessage(msg);
	        }
	        
		}
	}
	
	
}
